/**
 * Created by wei on 17/11/7.
 * article 包含多个topic>replay>comment 及分页
 */

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import base from '../base.js';
import Publish from '../front/publish.js';
import Comment from '../front/comment.js';
import cookie from '../cookie.js';
import axios from 'axios';
import PropTypes from 'prop-types';
import Replay from '../front/replay';
import "../main.css";
const basePath = base().basePath;


class TipL extends  Component{


    render(){

        const {comment, height,nickname}  = this.props;

        return (
            <div className={nickname === comment.user.nickname ? 'tip-l-self tip-l-lay' : 'tip-l tip-l-lay'} style={{marginTop:height+'px'}}>
                <div style={{margin:'3px 7px', wordBreak:'keep-all', wordWrap:'break-word'}}>
                    <div style={{width:'100%'}}><a target="_blank" href={'/person.html#/?t='+comment.user.token}>{comment.user.nickname}</a>:</div>
                    <div style={{color:'#9b8878'}}>{comment.content}</div>
                </div>
            </div>
        );
    }
}

TipL.propTypes = {
    comment: PropTypes.object.isRequired,
    height: PropTypes.number.isRequired,
    nickname: PropTypes.string.isRequired,
};



class TipR extends  Component{


    render(){

        const {comment, height, nickname}  = this.props;
        // console.log("token:"+nickname+"  user.token:"+comment.user.nickname);
        return (
            <div className={nickname === comment.user.nickname ? 'tip-r-self tip-r-lay' : 'tip-r tip-r-lay'}  style={{marginTop:height+'px'}}>
                <div style={{margin:'3px 7px', wordBreak:'keep-all', wordWrap:'break-word'}}>
                    <div style={{width:'100%', marginLeft:'5px'}}><a target="_blank" href={'/person.html#/?t='+comment.user.token}>{comment.user.nickname}</a>:</div>
                    <div style={{color:'#9b8878'}}>{comment.content}</div>
                </div>
            </div>
        );
    }
}

TipR.propTypes = {
    comment: PropTypes.object.isRequired,
    height: PropTypes.number.isRequired,
    nickname: PropTypes.string.isRequired,
};

class ZArticles extends Component{

    constructor(props){
        super(props);
        const {topic, replays, userInfo} = this.props;
        this.state = {
            replayShow:false,
            commentShow:false,
            token: '',
            nickname: 'admin',
            topic:topic,
            replays:replays,
            userInfo:userInfo,
            height:0,
        }
    }

    componentWillReceiveProps(nextProps){
        const {topic, replays, userInfo} = nextProps;
        this.setState({
            topic:topic,
            replays:replays,
            userInfo:userInfo,
        })
    }

    componentDidMount(){
        var dom = ReactDOM.findDOMNode(this.refs.article);
        var height = dom.offsetHeight;

        this.setState({
            height: height,
        });
    }

    closeReplay(){
        this.setState({
            replayShow:false,
        });
        this.refresh();
    }

    closeComment(){
        this.setState({
            commentShow:false,
        });
        this.refresh();
    }

    refresh(){
        let topicId = this.state.topic.id;
        axios.get(basePath+"/topic/"+topicId+"/refresh", {headers: { token: this.state.token }
        }).then(
            (res) => {
                // console.log(JSON.stringify(res));
                var topic = res.data;
                var userInfo = topic.user;
                var replays = topic.replays;
                var comments = topic.comments;
                this.setState({
                    topic:topic,
                    userInfo: userInfo,
                    replays: replays,
                    comments: comments,
                });
            }
        );
    }

    tipOff(obj){
        if("t" === obj.type){
            axios.get(basePath+"/topic/"+obj.id+"/accusation", {headers: { token: this.state.token }
            }).then(
                (res) => {
                    alert("提交成功,感谢您的努力!");
                }
            );
        }else if("r" === obj.type){
            axios.get(basePath+"/replay/"+obj.id+"/accusation", {headers: { token: this.state.token }
            }).then(
                (res) => {
                    alert("提交成功,感谢您的努力!");
                }
            );
        }
    }

    delete(obj){
        if("t" === obj.type){
            axios.post(basePath+"/topic/sdel", {topicId:obj.id},{headers: { token: this.state.token }
            }).then(
                (res) => {
                    if(res.status == 200){

                    }
                }
            );
        }else if("r" === obj.type){
            axios.post(basePath+"/replay/sdel", {replayId:obj.id},{headers: { token: this.state.token }
            }).then(
                (res) => {
                    this.refresh();
                }
            );
        }
    }


    genComment(obj){
        if("r" === obj.type){
            axios.get(basePath+"/replay/"+obj.id+"/gen_comment",{headers: { token: this.state.token }
            }).then(
                (res) => {
                    this.refresh();
                }
            );
        }
    }


    like(obj){
        let id = obj.id;
        if(obj.type == 't'){
            axios.get(basePath+"/topic/"+obj.id+"/slike", {headers: { token: this.state.token }
            }).then(
                (res) => {
                    // this.refresh();
                    const topic = this.state.topic;
                    topic.like += 1;
                    topic.click = true;
                    this.setState({
                        topic: topic,
                    });
                }
            );
        }else{
            axios.get(basePath+"/replay/"+obj.id+"/slike", {headers: { token: this.state.token }
            }).then(
                (res) => {
                    // this.refresh();
                    var index = obj.index;
                    const replays = this.state.replays;
                    const  replay = replays[index];
                    replay.like += 1;
                    replay.click = true;
                    replays[index] = replay;
                    this.setState({
                        replays: replays,
                    });
                }
            );
        }
    }

    hate(obj){
        let id = obj.id;
        if(obj.type === 't'){
            axios.get(basePath+"/topic/"+obj.id+"/shate", {headers: { token: this.state.token }
            }).then(
                (res) => {
                    // this.refresh();
                    const topic = this.state.topic;
                    topic.hate += 1;
                    topic.click = true;
                    this.setState({
                        topic: topic,
                    });
                }
            );
        }else{
            axios.get(basePath+"/replay/"+obj.id+"/shate", {headers: { token: this.state.token }
            }).then(
                (res) => {
                    // this.refresh();
                    var index = obj.index;
                    const replays = this.state.replays;
                    const  replay = replays[index];
                    replay.hate += 1;
                    replay.click = true;
                    replays[index] = replay;
                    this.setState({
                        replays: replays,
                    });
                }
            );
        }
    }

    showReplay(){

        const {fnRegister} = this.props;
        const token = cookie.getCookie('token');
        const nickname = cookie.getCookie('nickname');
        if('' === this.state.token){
            if('' === token){
                fnRegister();
                return false;
            }else{
                this.setState({
                    token: token,
                    nickname: nickname,
                });
            }
        }

        this.setState({
            commentShow:false,
            replayShow:!this.state.replayShow,
        });
    }

    showComment(){

        const {fnRegister} = this.props;
        const token = cookie.getCookie('token');
        const nickname = cookie.getCookie('nickname');
        if('' === this.state.token){
            if('' === token){
                fnRegister();
                return false;
            }else{
                this.setState({
                    token: token,
                    nickname: nickname,
                });
            }
        }

        this.setState({
            replayShow:false,
            commentShow:!this.state.commentShow,
        });
    }

    genReplayArgs(content){
        var json = {};
        json.topicId = this.state.topic.id;
        json.content = content;
        json.token = this.state.token;
        return json;
    }

    genCommentArgs(content){
        var json = {};
        json.topicId = this.state.topic.id;
        json.content = content;
        json.token = this.state.token;
        return json;
    }

    getFirstFoot(){

        let topicZan;
        let topicCai;
        topicZan = (
            <a href="javascript:void(0);" onClick={this.like.bind(this,{id:this.state.topic.id, type:'t'})}>
                <img src="/images/zan.png"/><span>{this.state.topic.like}</span>
            </a>
        );
        topicCai = (
            <a href="javascript:void(0);" onClick={this.hate.bind(this,{id:this.state.topic.id, type:'t'})}>
                <img src="/images/zan.png" className="cai"/><span>{this.state.topic.hate}</span>
            </a>
        );

        if(this.state.replays.length > 0){
            return (
                <div className="foot">
                    {topicZan}
                    {topicCai}
                    &nbsp;&nbsp;
                    <a onClick={this.delete.bind(this,{id:this.state.topic.id,type:'t'})}  href="javascript:void(0);"><span>删除</span></a>
                    <span style={{fontSize:'12px',marginLeft:'10px'}}>1楼</span>

                    <a  target="_blank" href={'/person.html#/?t='+this.state.replays[0].user.token} style={{float: 'right', marginRight: '10px'}}>
                        <img src={this.state.replays[0].user.avatar}/>
                    </a>
                    <a  target="_blank" href={'/person.html#/?t='+this.state.replays[0].user.token} style={{float: 'right', marginTop: '5px'}}>{this.state.replays[0].user.nickname}</a>
                    <span className="level float_r">L<span style={{fontSize:'10px'}}>{this.state.replays[0].user.level}</span></span>
                </div>
            );
        }else{
            return (
                <div className="foot">
                    {topicZan}
                    {topicCai}
                    &nbsp;&nbsp;
                    <a onClick={this.delete.bind(this,{id:this.state.topic.id,type:'t'})} href="javascript:void(0);"><span>删除</span></a>
                    &nbsp;&nbsp;

                    <a href="javascript:void(0);" onClick={this.showReplay.bind(this)} class="btn2 float_r">回复</a>
                    <a href="javascript:void(0);" onClick={this.showComment.bind(this)} class="btn2 float_r">评论</a>
                    <div className="comments_header"></div>
                </div>
            );
        }
    }

    getFirstFootPub(){
        if(this.state.replays.length === 0){
            return (

                <Publish suspend={false} image={true} visible={this.state.replayShow} close={this.closeReplay.bind(this)} paramsGen={this.genReplayArgs.bind(this)} url={basePath+'/replay/add_back'}/>
            );
        }
    }

    getFirstFootComment(){
        if(this.state.replays.length === 0){
            return (
                <Comment close={this.closeComment.bind(this)}  paramsGen={this.genReplayArgs.bind(this)} url={basePath+'/comment/add_back'} visible={this.state.commentShow}/>
            );
        }
    }


    getReplayContent(){
        if(this.state.replays.length > 0){
            var contents = [];
            for(var i=0; i<this.state.replays.length-1; i++){


                let replayZan;
                let replayCai;
                replayZan = (
                    <a href="javascript:void(0);" onClick={this.like.bind(this,{id:this.state.replays[i].id, type:'r', index: i})}>
                        <img src="/images/zan.png"/><span>{this.state.replays[i].like}</span>
                    </a>
                );

                replayCai = (
                    <a href="javascript:void(0);" onClick={this.hate.bind(this,{id:this.state.replays[i].id, type:'r', index: i})}>
                        <img src="/images/zan.png" className="cai"/><span>{this.state.replays[i].hate}</span>
                    </a>
                );

                let op = this.zezhao(this.state.replays[i].like, this.state.replays[i].hate);

                contents.push((
                    <div>
                        <Replay op={op} replay={this.state.replays[i]}/>
                        <div className="foot">
                            {replayZan}
                            {replayCai}
                            &nbsp;&nbsp;
                            <a  onClick={this.delete.bind(this,{id:this.state.replays[i].id,type:'r'})}  href="javascript:void(0);"><span>删除</span></a>
                            &nbsp;&nbsp;
                            <a  onClick={this.genComment.bind(this,{id:this.state.replays[i].id,type:'r'})}  href="javascript:void(0);"><span>转化为评论</span></a>
                            <span style={{fontSize:'12px',marginLeft:'10px'}}>{i+2}楼</span>
                            <a  target="_blank" href={'/person.html#/?t='+this.state.replays[i+1].user.token} style={{float: 'right', marginRight: '10px'}}>
                                <img src={this.state.replays[i+1].user.avatar}/>
                            </a>
                            <a  target="_blank" href={'/person.html#/?t='+this.state.replays[i+1].user.token} style={{float: 'right', marginTop: '5px'}}>{this.state.replays[i+1].user.nickname}</a>
                            <span className="level float_r">L<span style={{fontSize:'10px'}}>{this.state.replays[i+1].user.level}</span></span>
                        </div>
                    </div>
                ));
            }
            return contents;
        }
    }

    getLastReplayContent(){
        if(this.state.replays.length > 0){
            let length = this.state.replays.length -1;

            let replayZan;
            let replayCai;
            replayZan = (
                <a href="javascript:void(0);" onClick={this.like.bind(this,{id:this.state.replays[length].id, type:'r', index: length})}>
                    <img src="/images/zan.png"/><span>{this.state.replays[length].like}</span>
                </a>
            );

            replayCai = (
                <a href="javascript:void(0);" onClick={this.hate.bind(this,{id:this.state.replays[length].id, type:'r', index: length})}>
                    <img src="/images/zan.png" className="cai"/><span>{this.state.replays[length].hate}</span>
                </a>
            );

            let op = this.zezhao(this.state.replays[length].like, this.state.replays[length].hate);
            return (
                <div>
                    <Replay op={op} replay={this.state.replays[length]}/>

                    <div className="foot">
                        {replayZan}
                        {replayCai}
                        &nbsp;&nbsp;
                        <a onClick={this.delete.bind(this,{id:this.state.replays[length].id,type:'r'})}  href="javascript:void(0);"><span>删除</span></a>
                        &nbsp;&nbsp;
                        <a  onClick={this.genComment.bind(this,{id:this.state.replays[length].id,type:'r'})}  href="javascript:void(0);"><span>转化为评论</span></a>
                        <a href="javascript:void(0);" onClick={this.showReplay.bind(this)} class="btn2 float_r">回复</a>
                        <a href="javascript:void(0);" onClick={this.showComment.bind(this)} class="btn2 float_r">评论</a>
                        <div className="comments_header"></div>
                    </div>
                    <Comment paramsGen={this.genReplayArgs.bind(this)} close={this.closeComment.bind(this)} url={basePath+'/comment/add_back'} visible={this.state.commentShow}/>
                    <Publish suspend={false} image={true} visible={this.state.replayShow} close={this.closeReplay.bind(this)} paramsGen={this.genReplayArgs.bind(this)} url={basePath+'/replay/add_back'}/>
                </div>
            );
        }
    }

    follow(){
        axios.get(basePath+"/follow/"+this.state.topic.id+"/f", {headers: { token: this.state.token }
        }).then(
            (res) => {
                // this.refresh();
                if(res.status === 200){
                    var topic = this.state.topic;
                    topic.follow = true;
                    this.setState({
                        topic: topic,
                    });
                }
            }
        );
    }


    unfollow(){
        axios.get(basePath+"/follow/"+this.state.topic.id+"/c", {headers: { token: this.state.token }
        }).then(
            (res) => {
                // this.refresh();
                if(res.status === 200){
                    var topic = this.state.topic;
                    topic.follow = false;
                    this.setState({
                        topic: topic,
                    });
                }
            }
        );
    }

    zezhao(like, hate){
        var op = 10;
        var v2 = parseInt( (hate - like) / 2);
        var v = op - v2;
        if(0 < v && v<=10 ){
            return v;
        }else if(v <= 0){
            return 1;
        }else if(v > 10){
            op = 10;
        }
        return op;
    }


    render(){

        const comments = this.state.topic.comments;
        let leftComment = [],rightComment = [];
        if(comments && comments.length){
            let length = parseInt(comments.length/2);
            var marginTop = 0;
            var jiange = this.state.height === 0 ? 10 : parseInt(this.state.height/length);
            var that = this;
            comments.forEach(function (v, i, arr) {
                if(i === length){
                    marginTop = 0;
                }
                if(i < length){
                    rightComment.push(<TipR nickname={that.state.nickname} comment={v} height={marginTop}/>);
                    marginTop += jiange;
                }else{
                    leftComment.push(<TipL nickname={that.state.nickname}  comment={v} height={marginTop}/>);
                    marginTop += jiange;
                }
            });
        }



        let op = this.zezhao(this.state.topic.like, this.state.topic.hate);

        return (
            <div style={{width:'100%',overflow:'hidden'}}>
                <div className="float_l" style={{width:'19%'}}>
                    <div>&nbsp;</div>
                    {leftComment}
                </div>
                <div className="article float_l" ref="article" style={{width:'60%'}}>
                    <div className="con">
                        <div className="author">
                            <a  target="_blank" href={'/person.html#/?t='+this.state.userInfo.token} >
                                <img src={this.state.userInfo.avatar} alt=""/>
                            </a>
                            <a  target="_blank" href={'/person.html#/?t='+this.state.userInfo.token} ><h2>{this.state.userInfo.nickname}</h2></a>
                            <span className="level float_l">L<span style={{fontSize:'10px'}}>{this.state.userInfo.level}</span></span>
                            <a style={{float:'right', marginRight:'10px'}} target="_blank" href={'/topic.html#/?t='+this.state.topic.id}><h2>查看全文</h2></a>
                        </div>
                        <div className={'story'} ref="story_l">
                            <div className="tipfeng">
                                <div className={"format opac"+op} dangerouslySetInnerHTML={{__html: this.state.topic.content}}>

                                </div>
                            </div>
                        </div>
                        {this.getFirstFoot()}
                        {this.getFirstFootPub()}
                        {this.getFirstFootComment()}
                        {this.getReplayContent()}
                        {this.getLastReplayContent()}
                    </div>
                </div>
                <div className="float_r" style={{width:'19%'}}>
                    <div>&nbsp;</div>
                    {rightComment}
                </div>
            </div>
        );
    }
}



ZArticles.propTypes = {
    topic: PropTypes.object.isRequired,
    replays: PropTypes.array.isRequired,
    userInfo: PropTypes.object.isRequired,
};

export default ZArticles;